import { useEffect, useRef } from "react";
import {
    ArcRotateCamera, Color4, Engine, HemisphericLight, Mesh, MeshBuilder, Plane, Scene, StandardMaterial, Vector3, Color3, ShadowLight, SpotLight, Texture, UniversalCamera, FollowCamera, FlyCamera, Material, ShaderMaterial, PointLight, DirectionalLight, Light,
} from '@babylonjs/core';


const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const engine = new Engine(canvas, true);
const scene = new Scene(engine);


const camera = new ArcRotateCamera('Camera', Math.PI / 3, Math.PI / 3, 9, new Vector3(0, 0, 0), scene);
camera.attachControl(canvas, true);


const texture = new Texture("../image/image01.png", scene);
var material = new StandardMaterial("myMat", scene);

//半球光(模拟环境光)
// const light = new HemisphericLight('pxg', new Vector3(1, 1, 0), scene);

//点光
// const light = new PointLight('light01', new Vector3(-1, 1, 1), scene);

//平行光
// const light = new DirectionalLight('light02', new Vector3(-1, -1, 0), scene);

//锥形灯
const light = new SpotLight('light03', new Vector3(0, 10, 0), new Vector3(0, -1, 0), Math.PI / 3, 20, scene);
light.range = 100;//灯光长度
//投影纹理
light.projectionTexture = texture;

//灯光通用属性
// light.diffuse = new Color3(1, 0, 0);//漫反射
// light.specular = new Color3(0, 0, 1);//高光
// light.setEnabled(true);//开关
// light.intensity = 0.5;
// light.lightmapMode = Light.LIGHTMAP_DEFAULT;

//光照贴图
// material.useLightmapAsShadowmap = true;
// material.lightmapTexture = texture;//光照贴图,需要把useLightmapAsShadowmap打开
// material.maxSimultaneousLights = 6;//最大相应灯光数量,基础是4个



const ground = MeshBuilder.CreateGround('ground', { width: 10, height: 10, updatable: true }, scene);
const updateAction: ((time: number) => {})[] = [];


const sphere = MeshBuilder.CreateSphere('sphere', { segments: 10, diameter: 3 }, scene);
sphere.material = material;
sphere.position.set(0, 2, 0);


updateAction.push((time: number) => {
    // light.intensity = Math.sin(time / 200);

    return '';
});




const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
            ani(0);
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;

function ani(time: number) {
    updateAction.forEach((action) => {
        action(time);
    })
    scene.render();

    requestAnimationFrame(ani);
}